const xml2js = require("xml2js");
const sipUtils = require("../../../utils/sipUtils");

const log4js = require('../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const config = require("../../../db/config");
const settingModel = require("../../../model/setting");

/**
 * 生成目录命令
 */
module.exports={

    generate: async function (deviceInfo) {
        if(!settingModel.cache.server_realm){
            logger.error('[请求目录] 生成指令时发现参数异常, deviceInfo=', deviceInfo , ', constants.sip.option=', settingModel.cache);
        }
        if (!deviceInfo) {
            logger.error('设备未注册成功,deviceInfo=null');
            return null;
        }
        let callId = Math.round((new Date()).getTime() / 1000) + '';
        let SN = Math.round((new Date()).getTime() / 1000);
        const json = {
            Query: {
                CmdType: 'Catalog',
                SN,
                DeviceID: deviceInfo.deviceid
            }
        };
        const builder = new xml2js.Builder({
            xmldec: {
                'version': '1.0',
                'encoding': 'GB2312',
                'standalone': null
            }
        });
        const content = builder.buildObject(json) + '\r\n\r\n';

        let cseq = {};
        cseq.method = 'MESSAGE';
        cseq.seq = 20;

        let from = {
            name: undefined,
            uri: `sip:${settingModel.cache.sip_command_account}@${settingModel.cache.server_realm}`,
            params: {tag: sipUtils.rstring()}
        };
        let to = {
            name: undefined,
            uri: `sip:${deviceInfo.deviceid}@${settingModel.cache.server_realm}`
        };
        let host = deviceInfo.sip_command_host;
        let port = deviceInfo.sip_command_port;
        if(!host){
            host = settingModel.cache.sip_command_host;
            port = settingModel.cache.sip_command_port;
        }
        let uri = sipUtils.generateUri(deviceInfo.deviceid, null, null, host, port);
        logger.info(`deviceId=${deviceInfo.deviceid} 生成uri=${uri} ,content=`, content, uri, deviceInfo);

        let via = sipUtils.generateVia(deviceInfo.protocol, null, null);
        return {
            method: cseq.method, uri, version: config.sip.version,
            headers: {
                via, from, to, cseq,
                'call-id': callId,
                'Content-Type': 'Application/MANSCDP+xml',
                'expires': '3600',
                'Max-Forwards': 70,
                'User-Agent': config.sip.useragent
            }, content
        };
    }
};
